package com.imooc.ecommerce.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.imooc.ecommerce.account.AddressInfo;
import com.imooc.ecommerce.common.TableId;
import com.imooc.ecommerce.dao.EcommerceAddressDao;
import com.imooc.ecommerce.entity.EcommerceAddress;
import com.imooc.ecommerce.filter.AccessContext;
import com.imooc.ecommerce.service.IAddressService;
import com.imooc.ecommerce.vo.LoginUserInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 江黎
 * @date 2022/1/6 23:28
 **/
public class IAddressServiceImpl implements IAddressService {
    @Autowired
    private EcommerceAddressDao addressDao;

    @Override
    public TableId createAddressInfo(AddressInfo addressInfo) {
        // 不能直接从参数中获取用户id
        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();
        List<EcommerceAddress> ecommerceAddressList = addressInfo.getAddressItems().stream().map(e ->
                EcommerceAddress.to(loginUserInfo.getId(), e)).collect(Collectors.toList());
        List<EcommerceAddress> ecommerceAddresses = addressDao.saveAll(ecommerceAddressList);
        List<Long> ids = ecommerceAddresses.stream().map(EcommerceAddress::getId).collect(Collectors.toList());
        return new TableId(ids.stream().map(TableId.Id::new).collect(Collectors.toList()));
    }

    @Override
    public AddressInfo getCurrentAddressInfo() {
        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();
        List<EcommerceAddress> ecommerceAddressList = addressDao.findAllByUserId(loginUserInfo.getId());
        List<AddressInfo.AddressItem> addressItemList = ecommerceAddressList.stream().map(EcommerceAddress::toAddressItem).collect(Collectors.toList());
        return new AddressInfo(loginUserInfo.getId(), addressItemList);
    }

    @Override
    public AddressInfo getAddressInfoById(Long id) {
        EcommerceAddress ecommerceAddress = addressDao.findById(id).orElse(null);
        if (ecommerceAddress == null) {
            throw new RuntimeException("address is not exist");
        }
        return new AddressInfo(ecommerceAddress.getUserId(), Collections.singletonList(ecommerceAddress.toAddressItem()));
    }

    @Override
    public AddressInfo getAddressInfoByTableId(TableId tableId) {
        List<Long> ids = tableId.getIds().stream().map(TableId.Id::getId).collect(Collectors.toList());
        List<EcommerceAddress> ecommerceAddressList = addressDao.findAllById(ids);
        if (CollectionUtil.isEmpty(ecommerceAddressList)) {
            return new AddressInfo(-1L, Collections.emptyList());
        }
        List<AddressInfo.AddressItem> addressItems = ecommerceAddressList.stream().map(EcommerceAddress::toAddressItem).collect(Collectors.toList());
        return new AddressInfo(ecommerceAddressList.get(0).getUserId(), addressItems);
    }
}
